//
//  HelloWorldLayer.m
//  Assignment1Q3Q4
//
//  Created by LxL on 2012-10-17.
//  Copyright __MyCompanyName__ 2012. All rights reserved.
//


// Import the interfaces
#import "MainLayer.h"

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"

#pragma mark - HelloWorldLayer

// HelloWorldLayer implementation
@implementation MainLayer

// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	MainLayer *layer = [MainLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super's" return value
	if( (self=[super init]) ) {
		
        //create array of squares
        _sprites= [[NSMutableArray alloc]init];
        collisionCandidates=[[NSMutableArray alloc]init];
        _tree=[[QuadTree alloc]init];
        
        
        for(int i=0;i<100;i++)
        {
            SquareSprite *sprite=[[SquareSprite alloc] init];
            [_sprites addObject: sprite];
            [self addChild:sprite];
            
            //fromQuadTree
            [_tree.root AddContent:sprite];
        }
        
        
		[self schedule:@selector(update:)];
		
	}
	return self;
}

-(void) update:(ccTime)dt
{
//    //Brute Forte
//    for(SquareSprite *sprite in _sprites)
//    {
//        [sprite setColor:ccWHITE];
//        [sprite setOpacity:255];
//        [sprite update:dt];
//        
//        for(SquareSprite *otherSprite in _sprites)
//        {
//            if( otherSprite!=sprite){
//                [sprite checkCollideWith:otherSprite];
//            }
//        }
//    }
    
    //Quadtree
    ////////////////////////////////////
    ////////////////////////////////////
    for(SquareSprite *sprite in _sprites)
    {
        [sprite setColor:ccWHITE];
        [sprite setOpacity:255];
        [sprite update:dt];
        
        [_tree UpdateContent:sprite];
        
        [_tree GetCollisionCandidatesOf:sprite inArray:&collisionCandidates];
        for(SquareSprite *otherSprite in collisionCandidates)
        {
            if( otherSprite!=sprite){
                [sprite checkCollideWith:otherSprite];
            }
        }
        [collisionCandidates removeAllObjects];
    }
    /////////////////////////////////////
}


// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
    
    [_sprites release];
    [_tree release];
    [collisionCandidates release];
	
	// don't forget to call "super dealloc"
	[super dealloc];
}


@end
